//
//  YWReportTroubleManager.m
//  maintain
//
//  Created by 烟雨云渊 on 17/3/2.
//  Copyright © 2017年 ewin. All rights reserved.
//

#import "YWReportTroubleManager.h"
#import "YWReportTroubleDBManager.h"
#import "YWLoginTool.h"
#import "YWCommonTool.h"
#import "WMHttpTool.h"
#import "YWConst.h"
#import "YWMacro.h"
#import "YWReportTroubleModel.h"
#import "MJExtension.h"
#import "YWResourceManager.h"
#import "YWEquipment.h"
#import "YWEquipmentManager.h"
#import "YWLocation.h"
#import "YWBuildingManager.h"
#import "YWFloor.h"
#import "YWApartment.h"
#import "YWBuilding.h"
#import "YWLogRecordTool.h"
#import "YWMissionManager.h"
#import "YWCirculationManager.h"
#import "YWNotifyManager.h"
#import "YWEwinManager.h"
#import "YWEquipmentType.h"
#import <Bugly/Bugly.h>

static BOOL isUploading = NO;

@interface YWReportTroubleManager()
@property (nonatomic, strong) dispatch_group_t group;
//@property (nonatomic, strong) dispatch_queue_t serialQueue;
//@property (nonatomic, strong) dispatch_semaphore_t signal;
@end

@implementation YWReportTroubleManager
YWSingletonM(Manager)

- (dispatch_group_t)group{
    if (!_group) {
        _group = dispatch_group_create();
    }
    return _group;
}

//- (dispatch_queue_t)serialQueue{
//    if (!_serialQueue) {
//        _serialQueue = dispatch_queue_create("uploadReportTroubleSerialQueue", DISPATCH_QUEUE_SERIAL); //创建上传串行队列
//    }
//    return _serialQueue;
//}
//
//- (dispatch_semaphore_t)signal{
//    if (!_signal) {
//        _signal = dispatch_semaphore_create(1);
//    }
//    return _signal;
//}

- (BOOL)updateReportTroubleWithArray:(NSArray*)reportTroubleArray{
    return [[YWReportTroubleDBManager shareManager]updateReportTroubleWithArray:reportTroubleArray];
}

-(BOOL)updateReportTroubleStatus:(NSInteger)status troubleId:(NSInteger)troubleId{
    return [[YWReportTroubleDBManager shareManager] updateReportTroubleStatus:status troubleId:troubleId];
}

- (BOOL)updateReportTroubleIdAndSequence:(YWReportTroubleModel*)troubleJson originTroubleId:(NSInteger)originTroubleId{
    return [[YWReportTroubleDBManager shareManager] updateReportTroubleIdAndSequence:troubleJson originTroubleId:originTroubleId];
}

- (BOOL)setUploadFailWithReportTrouble:(YWReportTroubleModel*)reportTrouble{
    return [[YWReportTroubleDBManager shareManager] setUploadFailWithReportTrouble:reportTrouble];
}

- (BOOL)deleteReportTroubleWithTroubleId:(NSInteger)troubleId orUniqueTag:(NSString *)uniqueTag{
    return [[YWReportTroubleDBManager shareManager] deleteReportTroubleWithTroubleId:troubleId orUniqueTag:uniqueTag];
}

- (NSArray *)getMyReportTroubleWithPage:(NSInteger)page{
    return [[YWReportTroubleDBManager shareManager] getMyReportTroubleWithPage:page];
}

- (NSArray *)getMyReportTroubleWithAssignStatus:(BOOL)isAssign page:(NSInteger)page{
    return [[YWReportTroubleDBManager shareManager]getMyReportTroubleWithAssignStatus:isAssign page:page];
}

- (NSArray *)getReportTroubleUnassignBillsWithPage:(NSInteger)page{
    return [[YWReportTroubleDBManager shareManager] getReportTroubleUnassignBillsWithPage:page];
}

- (NSArray *)getReportTroubleWithEquipmentId:(NSString*)equipmentId page:(NSInteger)page{
    return [[YWReportTroubleDBManager shareManager] getReportTroubleWithEquipmentId:equipmentId page:page];
}

- (NSArray *)getReportTroubleWithLocationId:(NSInteger)locationId page:(NSInteger)page{
    return [[YWReportTroubleDBManager shareManager] getReportTroubleWithLocationId:locationId page:page];
}

- (YWReportTroubleModel*)getOneReportTroubleWithTroubleId:(NSInteger)troubleId{
    return [[YWReportTroubleDBManager shareManager] getOneReportTroubleWithTroubleId:troubleId];
}

- (NSArray*)uploadFailedReportTroubleArray{
    return [[YWReportTroubleDBManager shareManager] uploadFailedReportTroubleArray];
}

#pragma mark - 网络请求
- (void)requestMyReportTroubleWithPage:(NSInteger)page pageSize:(NSInteger)pageSize completeBlock:(void (^)(NSInteger))complete{
    //请求我的报障单
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(0);}return;}
    
    NSString *url = [YWCommonTool getMyReportTroubleUrl];
    NSMutableDictionary* params = [NSMutableDictionary dictionary];
    if (page) {
        [params setValue:@(page) forKey:@"page"];
    }
    if (pageSize) {
        [params setValue:@(pageSize) forKey:@"pageSize"];
    }
    YWLog(@"%@",params);
    [[WMHttpTool shareHttpTool] getWithUrl:url params:params success:^(NSHTTPURLResponse* response, id json) {
        NSArray* reportTroubleArray = [YWReportTroubleModel mj_objectArrayWithKeyValuesArray:json];
        [[YWReportTroubleManager shareManager] updateReportTroubleWithArray:reportTroubleArray];
        if (complete) {
            complete(reportTroubleArray.count);
        }
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        if (complete) {
            complete(0);
        }
        if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
        }
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
    }];
}

- (void)requestReportTroubleWithPage:(NSInteger)page pageSize:(NSInteger)pageSize troubleStatus:(NSString*)troubleStatus completeBlock:(void(^)(NSArray *reportTroubleArray))complete{
    //获取分配报障单（派单、已分派）
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(0);}return;}
    
    NSString *url = [YWCommonTool getReportTroubleAssignOrNotUrl];
    NSMutableDictionary* params = [NSMutableDictionary dictionary];
    if (page) {
        [params setValue:@(page) forKey:@"page"];
    }
    if (pageSize) {
        [params setValue:@(pageSize) forKey:@"pageSize"];
    }
    if (troubleStatus) {
        [params setValue:troubleStatus forKey:@"troubleStatus"];
    }
    YWLog(@"%@",params);
    [[WMHttpTool shareHttpTool] getWithUrl:url params:params success:^(NSHTTPURLResponse* response, id json) {
        NSArray* reportTroubleArray = [YWReportTroubleModel mj_objectArrayWithKeyValuesArray:json];
        [[YWReportTroubleManager shareManager] updateReportTroubleWithArray:reportTroubleArray];
        
//        __block NSString *lastDate = nil;
//        __block NSMutableArray *array = nil;
//        __block NSMutableArray * troubleArray = [NSMutableArray array];
//        [reportTroubleArray enumerateObjectsUsingBlock:^(YWReportTroubleModel * _Nonnull reportTrouble, NSUInteger idx, BOOL * _Nonnull stop) {
//            NSString *timeDate = [YWCommonTool showChineseFormatterDate:reportTrouble.reportTime/1000];
//            if (lastDate==nil || ![timeDate isEqualToString:lastDate]) {
//                lastDate = timeDate;
//                array = [NSMutableArray array];
//            }
//            [array addObject:reportTrouble];
//            if (![troubleArray containsObject:array] && array.count) {
//                [troubleArray addObject:array];
//            }
//        }];

        if (complete) {
            complete(reportTroubleArray);
        }
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        if (complete) {
            complete(0);
        }
        if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
        }
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
    }];
}

- (void)requestReportTroubleWithDictionary:(NSMutableDictionary*)params completeBlock:(void(^)(NSArray *reportTroubleArray))complete{
    //获取所有报障单（抢单、记录）
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(0);}return;}
    
    NSString *url = [YWCommonTool getReportTroubleBillsOrRecords];
    YWLog(@"url:%@,params:%@",url,params);
    [[WMHttpTool shareHttpTool] getWithUrl:url params:params success:^(NSHTTPURLResponse* response, id json) {
        NSArray* reportTroubleArray = [YWReportTroubleModel mj_objectArrayWithKeyValuesArray:json];
        [[YWReportTroubleManager shareManager] updateReportTroubleWithArray:reportTroubleArray];
        
//        __block NSString *lastDate = nil;
//        __block NSMutableArray *array = nil;
//        __block NSMutableArray * troubleArray = [NSMutableArray array];
//        [reportTroubleArray enumerateObjectsUsingBlock:^(YWReportTroubleModel * _Nonnull reportTrouble, NSUInteger idx, BOOL * _Nonnull stop) {
//            NSString *timeDate = [YWCommonTool showChineseFormatterDate:reportTrouble.reportTime/1000];
//            if (lastDate==nil || ![timeDate isEqualToString:lastDate]) {
//                lastDate = timeDate;
//                array = [NSMutableArray array];
//            }
//            [array addObject:reportTrouble];
//            if (![troubleArray containsObject:array] && array.count) {
//                [troubleArray addObject:array];
//            }
//        }];
        
        if (complete) {
            complete(reportTroubleArray);
        }
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        if (complete) {
            complete(0);
        }
        if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
        }
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
    }];
}

//请求设备报障记录
- (void)requestPostTroubleWithEquipmentId:(NSString*)equipmentId page:(NSInteger)page pageSize:(NSInteger)pageSize completeBlock:(void(^)(BOOL success))complete{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(NO);}return;}
    
    NSString *url = [YWCommonTool getEquipmentTroubleRecordUrl];
    NSMutableDictionary* params = [NSMutableDictionary dictionary];
    if (equipmentId) {
        [params setValue:equipmentId forKey:@"equipmentId"];
    }
    if (pageSize) {
        [params setValue:@(pageSize) forKey:@"pageSize"];
    }
    if (page) {
        [params setValue:@(page) forKey:@"page"];
    }
    YWLog(@"%@",params);
    [[WMHttpTool shareHttpTool] getWithUrl:url params:params success:^(NSHTTPURLResponse* response, id json) {
        NSArray* reportTroubleArray = [YWReportTroubleModel mj_objectArrayWithKeyValuesArray:json];
        [[YWReportTroubleManager shareManager] updateReportTroubleWithArray:reportTroubleArray];
        if (complete) {
            complete(YES);
        }
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        if (complete) {
            complete(NO);
        }
        if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
        }
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
    }];
}

//请求地址报障记录
- (void)requestPostTroubleWithLocationId:(NSInteger)locationId page:(NSInteger)page pageSize:(NSInteger)pageSize completeBlock:(void(^)(BOOL success))complete{
    [WMHttpTool shareHttpTool].HTTPHeaders = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    NSMutableDictionary* params = [NSMutableDictionary dictionary];
    if (locationId) {
        [params setValue:@(locationId) forKey:@"locationId"];
    }
    if (pageSize) {
        [params setValue:@(pageSize) forKey:@"pageSize"];
    }
    if (page) {
        [params setValue:@(page) forKey:@"page"];
    }
    NSString *url = [YWCommonTool getLocationTroubleRecordUrl];
    YWLog(@"url:%@,params:%@",url,params);
    [[WMHttpTool shareHttpTool] getWithUrl:url params:params success:^(NSHTTPURLResponse* response, id json) {
        NSArray* reportTroubleArray = [YWReportTroubleModel mj_objectArrayWithKeyValuesArray:json];
        [[YWReportTroubleManager shareManager] updateReportTroubleWithArray:reportTroubleArray];
        if (complete) {
            complete(YES);
        }
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        if (complete) {
            complete(NO);
        }
        if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
        }
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
    }];
}

#pragma mark --- 上传报障记录
- (void)startUploadReportTrouble:(YWReportTroubleModel*)reportTrouble pictures:(NSArray*)pictures{
    if (!reportTrouble) {
        return;
    }
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        dispatch_group_enter(self.group);
        if (pictures.count>0) {
            [[YWResourceManager shareManager]
             uploadLocalPictureToAliyunOSS:pictures isAvatar:NO complete:^(BOOL isError, NSArray* uploadPictures) {
                 [self missionCompleteHandleWithReportTrouble:reportTrouble uploadPictures:uploadPictures error:isError];
             }];
        }else{
            [self missionCompleteHandleWithReportTrouble:reportTrouble uploadPictures:nil error:NO];
        }
        dispatch_group_wait(self.group, DISPATCH_TIME_FOREVER);
    });
}

- (void)missionCompleteHandleWithReportTrouble:(YWReportTroubleModel*)reportTrouble uploadPictures:(NSArray*)uploadPictures error:(BOOL)isError{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [[YWResourceManager shareManager] savePicturesToDBWithArray:uploadPictures];
        if (!isError) {
            [self submitPostTroubleRequestWithMission:reportTrouble Pictures:uploadPictures];
        }else{
            //更新上传状态
            reportTrouble.uploadFail = YES;
            [[YWReportTroubleManager shareManager] setUploadFailWithReportTrouble:reportTrouble];
            dispatch_group_leave(self.group);
        }
    });
}

- (void)submitPostTroubleRequestWithMission:(YWReportTroubleModel*)reportTrouble Pictures:(NSArray*)pictures{
    NSDictionary *headers = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headers;
    if (headers == nil) {dispatch_group_leave(self.group);return;}
    NSMutableDictionary* params = [NSMutableDictionary dictionary];
    
    if (reportTrouble.uniqueTag) {
        [params setValue:reportTrouble.uniqueTag forKey:@"uniqueTag"];
    }
    YWEquipment* equipment = reportTrouble.equipment;//[[YWEquipmentManager shareManager] equipmentWithId:reportTrouble.equipment.equipmentId];
    if (equipment) {
        [params setValue:@(equipment.locationId) forKey:@"location.locationId"];
        [params setValue:@(equipment.equipmentTypeId) forKey:@"equipmentType.equipmentTypeId"];
        if (![reportTrouble.equipment.equipmentId isEqualToString:@"位置报障"]) {
            [params setValue:reportTrouble.equipment.equipmentId ?: @"" forKey:@"equipment.equipmentId"];
        }
    }
    if (reportTrouble.qrcodeId.length) {
        [params setValue:reportTrouble.qrcodeId forKey:@"qrcodeId"];
    }
    [params setValue:reportTrouble.note?:@"" forKey:@"note"];
    
    YWLocation *location = [[YWBuildingManager shareManager] locationWithId:reportTrouble.location.locationId];
    if (location) {
        if (location.locationId>0) {
            [params setValue:@(location.locationId) forKey:@"location.locationId"];
        }else{
            [params setValue:location.locationName?:@"" forKey:@"location.locationName"];
        }
        YWFloor *floor = [[YWBuildingManager shareManager] floorWithId:location.floorId];
        if (floor) {
            if (floor.floorId>0) {
                [params setValue:@(floor.floorId) forKey:@"floor.floorId"];
            }else{
                [params setValue:floor.floorName?:@"" forKey:@"floor.floorName"];
            }
        }
        YWApartment *apartment = [[YWBuildingManager shareManager] apartmentWithId:floor.apartmentId];
        if (apartment) {
            if (apartment.apartmentId>0) {
                [params setValue:@(apartment.apartmentId) forKey:@"apartment.apartmentId"];
            }else{
                [params setValue:apartment.apartmentName?:@"" forKey:@"apartment.apartmentName"];
            }
        }
    }
    
    YWBuilding* building = reportTrouble.building;
    if (building == nil) {
        building = [[YWBuildingManager shareManager] buildingWithEquipmentId:reportTrouble.equipment.equipmentId];
    }
    if (building == nil) {
        building = [[YWBuildingManager shareManager] buildingWithLocationId:reportTrouble.location.locationId];
    }
    //报障系统类型
    if (reportTrouble.systemTypeId != 0) {
        [params setValue:@(reportTrouble.systemTypeId) forKey:@"systemTypeId"];
    }
    NSString *buildingId = building.buildingId.length>0 ? building.buildingId: reportTrouble.building.buildingId;
    [params setValue:buildingId.length>0 ? buildingId:@"" forKey:@"building.buildingId"];
    
    [pictures enumerateObjectsUsingBlock:^(YWPicture* _Nonnull picture, NSUInteger idx, BOOL* _Nonnull stop) {
        [params setValue:picture.bigPictureUrl ?: @"" forKey:[NSString stringWithFormat:@"pictures[%lu].url", (unsigned long)idx]];
        [params setValue:picture.smallPictureUrl ?: @"" forKey:[NSString stringWithFormat:@"pictures[%lu].thumbnailUrl", (unsigned long)idx]];
        [params setValue:picture.smallPictureUrl ?: @"" forKey:[NSString stringWithFormat:@"pictures[%lu].previewUrl", (unsigned long)idx]];
    }];
    NSString *url = [YWCommonTool getSubmitPostTroubleUrl];
    YWLog(@"url -- %@,%@",url,params);
    //保存请求前的参数日志
    NSString *logTag = [YWCommonTool randStringId];
    NSMutableDictionary * logDic = [[YWLogRecordTool shareLogRecordManager] getLogDictionaryWithModule:@"报障" interface:url params:params headers:headers tag:logTag];
    [[YWLogRecordTool shareLogRecordManager] saveLocalPatameterLog:logDic];
    
    [[WMHttpTool shareHttpTool] postWithUrl:url params:params success:^(NSHTTPURLResponse* response, id json) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            YWLog(@"post reportTrouble upload success");
            YWReportTroubleModel* reportTroubleJson = [YWReportTroubleModel mj_objectWithKeyValues:json];
            if (reportTroubleJson) {
                //保存流转信息
                [[YWCirculationManager shareManager] updateCirculationInfoWithArray:reportTroubleJson.circulationInfos];
            }
            //保存 录入的报障的新建的位置
            if (reportTroubleJson.equipment == nil && reportTroubleJson.channel == YWReportTroubleTypeEwinApp) {
                [[YWDBTool shareDBTool] updateIdAndNameWithBuilding:reportTroubleJson.building apartment:reportTroubleJson.apartment floor:reportTroubleJson.floor location:reportTroubleJson.location];
            }
            reportTrouble.uploadFail = 0;
            [self setUploadFailWithReportTrouble:reportTrouble];
            [[YWReportTroubleManager shareManager]  updateReportTroubleIdAndSequence:reportTroubleJson originTroubleId:reportTrouble.troubleId];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [[YWNotifyManager shareManager] postTroubleNotifyWithStatu:reportTrouble.equipment.equipmentId];
            });
            
            [[YWEwinManager shareManager] addTotalCountWithType:YWUnReadCountTypeTrouble];
            //保存请求成功的参数日志
            NSMutableDictionary * successDic =
            [[YWLogRecordTool shareLogRecordManager] successOrFailedLogDicWith:logDic statusCode:response.statusCode errorInfo:@"无" logTag:logTag];
            [[YWLogRecordTool shareLogRecordManager] saveLocalPatameterLog:successDic];
            dispatch_group_leave(self.group);
        });
        
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            YWLog(@"%s,error:%@", __func__, error.localizedDescription);
            //保存请求失败的参数日志
            NSString * result = [NSString stringWithFormat:@"%s,error:%@", __func__, error.localizedDescription];
            NSMutableDictionary * failedDic = [[YWLogRecordTool shareLogRecordManager] successOrFailedLogDicWith:logDic statusCode:response.statusCode errorInfo:result logTag:logTag];
            [[YWLogRecordTool shareLogRecordManager] saveLocalPatameterLog:failedDic];
            
            //上传错误参数
            if ([[WMHttpTool shareHttpTool] existenceNetwork]) {
                NSString *statusCode = [NSString stringWithFormat:@"statusCode: %@",@(response.statusCode).stringValue];
                [Bugly reportException:[NSException exceptionWithName:@"报障接口错误" reason:statusCode userInfo:params]];
            }
            
            //更新上传状态
            reportTrouble.uploadFail = YES;
            if (params && (response.statusCode==404 || response.statusCode==400)) {
                NSInteger locationId = [[params objectForKey:@"location.locationId"] integerValue];
                NSString *locationName = [[params objectForKey:@"location.locationName"] stringValue];
                if (locationId == 0 && locationName.length==0) {
                    //录入的报障有问题，没有位置信息，删除错误的数据
                    YWLog(@"error:录入的报障有问题，没有位置信息,请注意!!!");
                    [[YWReportTroubleManager shareManager] deleteReportTroubleWithTroubleId:reportTrouble.troubleId orUniqueTag:reportTrouble.uniqueTag];
                }
            }
            [[YWReportTroubleManager shareManager] setUploadFailWithReportTrouble:reportTrouble];
            dispatch_group_leave(self.group);
        });
    }];
}
                   
- (void)startUnUploadReportTrouble{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        if (![YWLoginTool isLogin]) {
            return;
        }
        if (isUploading == YES) {
            return;
        }
        isUploading = YES;
        
        NSArray * uploadFailReportTroubles = [self uploadFailedReportTroubleArray];
        [uploadFailReportTroubles enumerateObjectsUsingBlock:^(YWReportTroubleModel* _Nonnull reportTrouble, NSUInteger idx, BOOL* _Nonnull stop) {
            //报障图片
            NSArray* pictures = [[YWDBTool shareDBTool] picturesWithMissionId:reportTrouble.troubleId maintenanceType:YWMaintenanceTypeTrouble];
            
            dispatch_group_enter(self.group);
            if (pictures.count>0) {
                [[YWResourceManager shareManager]
                 uploadLocalPictureToAliyunOSS:pictures isAvatar:NO complete:^(BOOL isError, NSArray* uploadPictures) {
                     [self missionCompleteHandleWithReportTrouble:reportTrouble uploadPictures:uploadPictures error:isError];
                 }];
            }else{
                [self missionCompleteHandleWithReportTrouble:reportTrouble uploadPictures:nil error:NO];
            }
            dispatch_group_wait(self.group, DISPATCH_TIME_FOREVER);
            
            if (idx == uploadFailReportTroubles.count-1) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [[NSNotificationCenter defaultCenter] postNotificationName:KPushBackgroundUploadRecordSuccessNotification object:nil];
                });
            }
        }];
        isUploading = NO;
    });
}

- (void)postSubscriptionOptionsWithlocationArray:(NSMutableArray*)locationArray systemArray:(NSMutableArray*)systemArray  WithComplete:(void(^)(BOOL success))complete{
    NSDictionary *headers = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headers;
    if (headers == nil) {
        return;}
    NSMutableDictionary* params = [NSMutableDictionary dictionary];
    NSMutableArray * buildingArray = [NSMutableArray array];
    NSMutableArray * apartmentArray = [NSMutableArray array];
    for (id obj in locationArray) {
        if ([obj isKindOfClass:[YWBuilding class]]) {
            YWBuilding * building = (YWBuilding*)obj;
            [buildingArray addObject:building];
        }else if ([obj isKindOfClass:[YWApartment class]]){
            YWApartment *apartment = (YWApartment*)obj;
            [apartmentArray addObject:apartment];
        }
    }
    NSMutableString *buildingIds = [[NSMutableString alloc] init];
    [buildingArray enumerateObjectsUsingBlock:^(YWBuilding*  _Nonnull building, NSUInteger idx, BOOL * _Nonnull stop) {
        if (building.buildingId.length && idx!=0) {
            [buildingIds appendString:@","];
        }
        [buildingIds appendString:building.buildingId];
    }];
    
    NSMutableString *apartmentIds = [[NSMutableString alloc] init];
    [apartmentArray enumerateObjectsUsingBlock:^(YWApartment*  _Nonnull apartment, NSUInteger idx, BOOL * _Nonnull stop) {
        if (apartment.apartmentId != 0 && idx!=0) {
            [apartmentIds appendString:@","];
        }
        [apartmentIds appendString:[@(apartment.apartmentId) stringValue]];
    }];
    NSMutableString *systemTypeIds = [[NSMutableString alloc] init];
    [systemArray enumerateObjectsUsingBlock:^(YWEquipmentSystemType*  _Nonnull systemType, NSUInteger idx, BOOL * _Nonnull stop) {
        if (systemType.systemTypeId != 0 && idx!=0) {
            [systemTypeIds appendString:@","];
        }
        [systemTypeIds appendString:[@(systemType.systemTypeId) stringValue]];
    }];
    [params setValue:buildingIds?: @"" forKey:@"buildingIds"];
    [params setValue:apartmentIds?: @"" forKey:@"apartmentIds"];
    [params setValue:systemTypeIds?: @"" forKey:@"systemTypeIds"];
    NSString * url = [YWCommonTool postSubscriptionReportTroubleUrl];
    YWLog(@"url -- %@,%@",url,params);
    [[WMHttpTool shareHttpTool] postWithUrl:url params:params success:^(NSHTTPURLResponse *response, id json) {
        YWLog(@"post subscription upload success");
        if (complete) {
            complete(YES);
        }
    } failure:^(NSHTTPURLResponse *response, NSError *error) {
        YWLog(@"post subscription upload failure");
        if (complete) {
            complete(NO);
        }
    }];     
}

@end
